//
//  Created by Rene Dohan on 11/23/11.
//

#import "TransactionRequest.h"
#import "Lang.h"
#import "TransactionsListener.h"
#import "LoadRowRequest.h"
#import "MBProgressHUD.h"

@implementation TransactionRequest {
    NSInteger requestIndex;
    NSMutableArray *loadRowRequests;
    BOOL loaded;
}

@synthesize transactionsListener;

- (id)init {
    loadRowRequests = [NSMutableArray new];
    return [super init];
}

- (NSInteger)index {
    return requestIndex;
}

- (void)setIndex:(NSInteger)anIndex {
    requestIndex = anIndex;
    [self addArgument:@"from" :[Lang asStringInt:anIndex * 30]];
    [self addArgument:@"to" :[Lang asStringInt:anIndex * 30 + 30]];
}

- (NSDictionary *)getDataFor:(NSInteger)index {
    index = index - index / 30 * 30;
    NSArray *rows = (NSArray *) [self.data objectForKey:@"rows"];
    return [rows objectAtIndex:index];
}

- (void)onResultsReady:(NSDictionary *)results {
    loaded = true;
    [super onResultsReady:results];
    for (LoadRowRequest *loadRowRequest in loadRowRequests) {
        if (loadRowRequest.valid) {
            [transactionsListener onRowDataReady:[self getDataFor:loadRowRequest.rowIndex] :loadRowRequest];
            [MBProgressHUD hideHUDForView:loadRowRequest.cell animated:true];
        }
    }
}

- (void)addLoadRowRequest:(LoadRowRequest *)loadRowRequest {
    if (loaded) {
        [transactionsListener onRowDataReady:[self getDataFor:loadRowRequest.rowIndex] :loadRowRequest];
    } else {
        [MBProgressHUD showHUDAddedTo:loadRowRequest.cell animated:true];
        [loadRowRequests addObject:loadRowRequest];
    }
}

@end